package org.tony.common.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

@SuppressWarnings("unchecked")
public final class FileUtil
{

  public static final <T> T readObject(String path, Class<T> clazz) throws Exception
  {
    File file = new File(ResourcesHelper.getResourceURI(path));
    if (!file.exists())
    {
      file.getParentFile().mkdirs();
      try
      {
        file.createNewFile();
      }
      catch (IOException e)
      {
        return null;
      }
    }

    ObjectInputStream ois = null;
    try
    {
      ois = new ObjectInputStream(new FileInputStream(file));
      Object obj = ois.readObject();
      if (obj != null && obj.getClass().isAssignableFrom(clazz))
      {
        return (T)obj;
      }
    }
    catch (Exception e)
    {
      throw new FileOperateException(e.getCause());
    }
    finally
    {
      if (ois != null)
      {
        ois.close();
      }
    }
    return null;
  }

  public static final void writeObject(String path, Object obj) throws Exception
  {
    File file = new File(ResourcesHelper.getResourceURI(path));
    if (!file.exists())
    {
      file.getParentFile().mkdirs();
      try
      {
        file.createNewFile();
      }
      catch (IOException e)
      {
        throw new FileOperateException(e.getCause());
      }
    }

    ObjectOutputStream oos = null;
    try
    {
      oos = new ObjectOutputStream(new FileOutputStream(file));
      oos.writeObject(obj);
      oos.flush();
    }
    catch (Exception e)
    {
      throw new FileOperateException(e.getCause());
    }
    finally
    {
      try
      {
        oos.close();
      }
      catch (IOException e)
      {
        //close failed
      }
    }

  }
}
